<template>
	<view class="container">
		<Navigator2 :title="$t('device.deviceSettingGuide')"></Navigator2>
		
		<!-- 步骤指示器 -->
		<view class="step-indicator">
			<view class="step-item">
				<view class="step-circle">1</view>
				<text class="step-text">{{ $t('device.devicePowerOn') }}</text>
			</view>
			<view class="step-line"></view>
			<view class="step-item">
				<view :class="networkType == '' ? 'step-circle active' : 'step-circle'">2</view>
				<text :class="networkType == '' ? 'step-text active' : 'step-text'">{{ $t('device.connectDevice') }}</text>
			</view>
			<view class="step-line"></view>
			<view class="step-item">
				<view :class="networkType == '' ? 'step-circle' : 'step-circle active'">3</view>
				<text :class="networkType == '' ? 'step-text' : 'step-text active'">{{ $t('device.connectNetwork') }}</text>
			</view>
		</view>
		
		<!-- 蓝牙搜索图片 -->
		<view class="device-image">
			<template v-if="connecting || setupNetworkStatus == 1">
				<image v-if="networkType == ''" src="/static/BLUETOOTH.gif" mode="aspectFit"></image>
				<image v-if="networkType == 'WIFI'" src="/static/WIFI.gif" mode="aspectFit"></image>
				<image v-if="networkType == '4G'" src="/static/4G.gif" mode="aspectFit"></image>
			</template>
			<template v-else>
				<image v-if="setupNetworkStatus == 2" src="/static/setupnetworksuccess.png" mode="aspectFit"></image>
				<image v-if="setupNetworkStatus == 3" src="/static/setupnetworkfail.png" mode="aspectFit"></image>
			</template>
		</view>
		
		<template v-if="networkType == ''">
			<!-- 搜索状态 -->
			<view v-if="!isFound && networkType == ''" class="search-status">
				<text>{{ $t('device.searchingDevice') }}</text>
			</view>
			
			<!-- 连接蓝牙区域 -->
			<view v-if="isFound && networkType == ''" class="bluetooth-section">
				<view class="bluetooth-title">
					<image src="/static/guide-link-bluetooth.png" class="bluetooth-icon" mode="aspectFit"></image>
					<text>{{ $t('device.connectBluetooth') }}</text>
				</view>
				
				<!-- 设备连接框 -->
				<view class="device-card">
					<view class="device-info">
						<view class="device-name">
							<text class="device-title">{{ $t('device.deviceBluetoothName') }}</text>
							<picker class="device-value" @change="bindBleChange" :value="currDeviceIndex" :range="deviceArray">
								<view class="uni-input">{{currDeviceID}}</view>
							</picker>
						</view>
						<text class="device-tip">{{ $t('device.pleaseEnsureThePhoneBluetoothIsTurnedOn') }}</text>
					</view>
				</view>
			</view>
			
			<!-- 底部固定区域 -->
			<view class="bottom-section">
				<!-- 下一步按钮 -->
				<view class="next-button" @click="nextStep">
					<text>{{ $t('device.nextStep') }}</text>
				</view>
			</view>
		</template>

		<template v-if="networkType != ''">
			<!-- 搜索状态 -->
			<view class="search-status">
				<text v-if="setupNetworkStatus == 1">{{ $t('device.networkConnecting') }}</text>
				<text v-if="setupNetworkStatus == 2">{{ $t('device.networkConnectedSuccess') }}</text>
				<text v-if="setupNetworkStatus == 3">{{ $t('device.networkConnectedFailed') }}</text>
			</view>
			
			<!-- 连接网络区域 -->
			<view class="network-type">
				<text v-if="setupNetworkStatus != 3">{{ $t('device.networkType') }}:{{ networkType }}</text>
				<text v-if="setupNetworkStatus == 3 && setupNetworkResult != ''">{{ setupNetworkResult }}</text>
			</view>

			<view class="container log-list" style="font-size: 10px;">
				<block v-for="(log, index) of logs" :key="index">
					<text class="log-item">{{log}}</text><br />
				</block>
			</view>
			
			<!-- 底部固定区域 -->
			<view v-if="!connecting" class="bottom-section">
				<!-- 下一步按钮 -->
				<view class="confirm-button" @click="confirm">
					<text>{{ $t('device.confirm') }}</text>
				</view>
			</view>
		</template>
		
		<!-- 蓝牙权限弹框 -->
		<neil-modal 
			:show="showBluetoothPermissionModal" 
			@close="closeBluetoothPermissionModal"
			:showCancel="true"
			:cancelText="$t('device.close')"
			:confirmText="$t('device.goToSettings')"
			cancelColor="#000000"
			confirmColor="#0256FF"
			@cancel="closeBluetoothPermissionModal"
			@confirm="goToSettings"
			:autoClose="false">
			<view class="bluetooth-modal-content">
				<text class="bluetooth-modal-title">{{ $t('device.smartDoll') }} {{ $t('device.wantToUseBluetoothForNewConnection') }}</text>
				<text class="bluetooth-modal-text">{{ $t('device.youCanAllowNewConnectionIn') }} {{ $t('device.settings') }}</text>
			</view>
		</neil-modal>
		<neil-modal :show="showWifiModal" v-if="showWifiModal" @close="closeWifiModal" :title="$t('device.pleaseEnterWifiPassword')" @cancel="closeWifiModal"
			@confirm="saveWifi" :confirmText="$t('device.confirm')" :cancelText="$t('device.cancel')" :showCancel="true">
			<view class="input-view">
				<view class="input-name">
					<view class="modal_wifiname">{{ $t('device.wifiName') }}:<text>{{ssid}}</text></view>
					<input type="text" v-model="pass" :placeholder="$t('device.pleaseEnterPassword')" :placeholder-class="showWifiModal ? '' : 'opacityColor'" />
				</view>
				<view class="blank"></view>
			</view>
		</neil-modal>
		<neil-modal :show="showManualWifiModal" v-if="showManualWifiModal" @close="closeManualWifiModal" :title="$t('device.pleaseEnterWifiInformation')" @cancel="closeManualWifiModal"
			@confirm="saveWifi2">
			<view class="input-view">
				<view class="input-name">
					<input type="text" v-model="ssid2" :placeholder="$t('device.pleaseEnterWifiName')" :placeholder-class="showManualWifiModal ? '' : 'opacityColor'" />
					<input type="text" v-model="pass2" :placeholder="$t('device.pleaseEnterPassword')" :placeholder-class="showManualWifiModal ? '' : 'opacityColor'" />
				</view>
				<view class="blank"></view>
				<view class="blank"></view>
			</view>
		</neil-modal>
		<neil-modal :show="showTipModal" @close="closeTipModal" :title="$t('device.tip')" :confirm-text="$t('device.goToSettings')" @cancel="closeTipModal"
			@confirm="goToSettings">
			<view class="tipmodel_line">{{ $t('device.bluetoothInitializationFailed') }}</view>
			<view class="tipmodel_line">{{ $t('device.pleaseCheckIfThePhoneBluetoothIsTurnedOn') }}</view>
			<view class="blank"></view>
		</neil-modal>
	</view>
</template>

<script>
	import permision from "@/js_sdk/wa-permission/permission.js"
	import api from '../../js/api'
	import util from '../../js/util'
	import Navigator2 from '@/components/Navigator2.vue'
	import neilModal from '@/components/neil-modal/neil-modal.vue'
	export default {
		data() {
			return {
				platform: uni.getSystemInfoSync().platform,
				delayTimer: null,
				manualWifiDelay: null,
				timeout: null,
				isFound: false,
				recvData: [],
				ssid: '',
				pass: '',
				ssid2: '',
				pass2: '',
				logs: [],
				deviceArray: [],
				currDeviceID: this.$t('device.pleaseSelect'),
				currDeviceIndex: 0,
				searchStatus: false,
				connectStatus: false,
				connecting: true,

				setupNetworkStatus: 1,
				setupNetworkResult: '',
				showWifiModal: false,
				showManualWifiModal: false,
				showTipModal: false,
				showBluetoothPermissionModal: false,
				linknetwork: false,
				networkType: '',
				wifiList: [],
				CrcCCITTTable: [
					0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7,
					0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF,
					0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6,
					0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE,
					0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, 0x5485,
					0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D,
					0x3653, 0x2672, 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4,
					0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC,
					0x48C4, 0x58E5, 0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823,
					0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B,
					0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12,
					0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A,
					0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41,
					0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49,
					0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70,
					0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78,
					0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F,
					0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067,
					0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E,
					0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256,
					0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D,
					0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
					0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C,
					0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634,
					0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB,
					0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3,
					0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A,
					0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92,
					0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9,
					0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1,
					0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8,
					0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0
				]
			}
		},
		onUnload() {
			//断开蓝牙
			// uni.hideLoading();
			uni.closeBluetoothAdapter({
				success: function(res) {
					console.log(res)
				}
			})
		},
		mounted() {
			this.checkBlePermission()
		},
		onShow() {
			uni.onGetWifiList(wifiList => {
				console.log('onGetWifiList:', wifiList)
				this.wifiList = wifiList.wifiList
				this.wifiList.sort((a, b) => b.signalStrength - a.signalStrength);
			})
		},
		onHide() {
			clearInterval(this.delayTimer)
			clearTimeout(this.timeout)
			// 注销WiFi监听器
			try {
				uni.offGetWifiList()
			} catch (e) {
				console.log('offGetWifiList error:', e)
			}
		},
		beforeRouteLeave() {
			clearInterval(this.delayTimer)
			clearTimeout(this.timeout)
		},
		beforeDestroy() {
			clearInterval(this.delayTimer)
			clearTimeout(this.timeout)
		},
		methods: {
			saveNetworkInfo() {
				if (this.networkType == 'WIFI') {
					const userInfo = uni.getStorageSync('userInfo')
					api.saveWifi(userInfo.phone, this.ssid, this.pass).then(res => {
						console.log('saveWifi success:', res)
					}).catch(err => {
						console.error('saveWifi error:', err)
					})
				}
			},
			checkBleIsAvailable() {
				uni.getBluetoothAdapterState({
					success: (res) => {
						console.log('getBluetoothAdapterState success:', res)
						if (res.available) {
							this.checkBlePermission()
						} else {
							this.showBluetoothPermissionModal = true
						}
					},
					fail: (err) => {
						console.error('getBluetoothAdapterState fail:', err)
						this.showBluetoothPermissionModal = true
					}
				})
			},
			async checkBlePermission() {
				if (this.platform == 'ios') {
					if (permision.judgeIosPermission("location")) {
						console.log('位置权限已授权')
						setTimeout(this.initBLE, 1000)
					} else {
						console.log('用户拒绝授权位置权限')
						uni.showToast({
							title: this.$t('device.pleaseAuthorizeLocationPermission'),
							icon: 'none'
						})
					}
				} else {
					var result = await permision.requestAndroidPermission("android.permission.ACCESS_COARSE_LOCATION")
					if (result == 1) {
						console.log('位置权限已授权')
						setTimeout(this.initBLE, 1000)
					} else if (result == 2) {
						console.log('用户拒绝授权位置权限')
						uni.showToast({
							title: this.$t('device.pleaseAuthorizeLocationPermission'),
							icon: 'none'
						})
					} else {
						console.log('用户已永久拒绝授权位置权限')
						uni.showToast({
							title: this.$t('device.pleaseAuthorizeLocationPermission'),
							icon: 'none'
						})
					}
				}
			},
			manualWifi() {
				this.showManualWifiModal = true
			},
			getWifiSignal(signalStrength) {
				if (this.platform == 'ios') {
					return signalStrength >= 0.8 ? '强' : (signalStrength >= 0.4 ? '中' : '弱')
				} else {
					return signalStrength >= 80 ? '强' : (signalStrength >= 40 ? '中' : '弱')
				}
			},
			getWifiLogoUrl(signalStrength) {
				if (this.platform == 'ios') {
					return signalStrength >= 0.8 ? '/static/wifi_3.png' : (signalStrength >= 0.4 ? '/static/wifi_2.png' : '/static/wifi_1.png')
				} else {
					return signalStrength >= 80 ? '/static/wifi_3.png' : (signalStrength >= 40 ? '/static/wifi_2.png' : '/static/wifi_1.png')
				}
			},
			nextStep() {
				let deviceID = this.currDeviceID;
				console.log("选中:" + deviceID);
				if (util.isEmpty(deviceID) || deviceID == this.$t('device.pleaseSelect')) {
					util.toastError(this.$t('device.pleaseSearchDevice'));
					return;
				}
				this.linknetwork = true

				deviceID = deviceID.split('[')[0];
				api.getDeviceType(deviceID).then(res => {
					console.log('getDeviceType is:', res)
					if (res == '1') {//wifi
						this.networkType = 'WIFI'
						this.getConnectedWifi()
					} else {//4G or wifi+4G
						this.networkType = '4G'
						this.notifyDeviceConnect4g()
					}
				}).catch(err => {
					console.error('getDeviceType error: ', err)
					this.networkType = 'WIFI'
					this.getConnectedWifi()
				})

			},
			notifyDeviceConnect4g() {
				// 通知设备用4G网络联网
				this.bleConfigEvent()
			},
			selectNetworkType(type) {
				this.networkType = type
			},
			getConnectedWifi() {
				uni.startWifi({
					success: (res) => {
						uni.getConnectedWifi({
							success: (res) => {
								console.log('getConnectedWifi is:', res)
								this.wifiList = [res.wifi]
								this.showWifiModalFun(res.wifi.SSID)
							},
							fail: (err) => {
								console.error('getConnectedWifi error: ', err)
								this.searchWifi()
							}
						})
					},
					fail: (err) => {
						console.error('startWifi error: ', err)
						this.searchWifi()
					}
				})
			},
			searchWifi() {
				if (this.platform == 'ios') {
					if (this.wifiList == null || this.wifiList.length == 0) {
						this.showManualWifiModal = true
					}
				} else {
					uni.startWifi({
						success: (res) => {
							uni.getWifiList({
								success: (res) => {
									console.log(res)
								},
								fail: (err) => {
									console.error(err)
									uni.showToast({
										icon: 'none',
										title: this.$t('device.pleaseOpenWifi'),
										duration: 2000
									})
								}
							})
						},
						fail: (err) => {
							console.error('startWifi error: ', err)
							uni.showToast({
								icon: 'none',
								title: this.$t('device.pleaseOpenWifi'),
								duration: 2000
							})
						}
					})
				}
			},
			bindBleChange(e) {
				this.currDeviceIndex = e.detail.value
				this.currDeviceID = this.deviceArray[e.detail.value]
			},
			bleConfigEvent() {
				let deviceID = this.currDeviceID;
				console.log("选中:" + deviceID);
				if (util.isEmpty(deviceID) || deviceID == this.$t('device.pleaseSelect')) {
					util.toastError(this.$t('device.pleaseSearchDevice'));
					return;
				}
				let device = deviceID.split('[');
				if (device.length <= 1) {
					util.toastError(this.$t('device.pleaseSearchDevice'));
					return;
				}
				let id = device[device.length - 1].replace("]", "");
				console.log(id);
				util.toastError(this.$t('device.connect') + id);
				this.createBLE(id);
			},
			initBLE() {
				this.printLog("启动蓝牙适配器, 蓝牙初始化")
				const that = this;
				uni.openBluetoothAdapter({
					success: function(res) {
						console.log(res);
						that.findBLE();
					},
					fail: function(res) {
						// util.toastError("请先打开蓝牙")
						console.log(res)
						that.showBluetoothPermissionModal = true
					}
				})
			},
			findBLE() {
				this.printLog("打开蓝牙成功.")
				const that = this
				uni.startBluetoothDevicesDiscovery({
					allowDuplicatesKey: false,
					interval: 0,
					success: function(res) {
						// uni.showLoading({
						// 	title: '正在搜索设备',
						// })
						console.log(res);
						that.searchStatus = true
						that.delayTimer = setInterval(function() {
							that.discoveryBLE() //3.0 //这里的discovery需要多次调用
						}, 1000);
						that.timeout = setTimeout(function() {
							// uni.hideLoading();
							uni.stopBluetoothDevicesDiscovery({
								success: function(res) {
									console.log('连接蓝牙成功之后关闭蓝牙搜索');
								}
							});
							clearInterval(that.delayTimer);
							that.searchStatus = false
							if (that.isFound) {
								return;
							} else {
								console.log("搜索设备超时");
								uni.showModal({
									title: this.$t('device.searchDeviceTimeout'),
									content: this.$t('device.pleaseCheckIfTheBluetoothDeviceIsWorking'),
									showCancel: false
								})
								util.toastError(this.$t('device.searchDeviceTimeout') + this.$t('device.pleaseOpenGpsLocation') + this.$t('device.pleaseSearchDevice'));
								return
							}
						}, 20000);
					},
					fail: function(res) {
						that.printLog("蓝牙设备服务发现失败: " + res.errMsg);
					}
				})
			},
			discoveryBLE() {
				const bleNamePrefix = 'JL'
				const that = this
				uni.getBluetoothDevices({
					success: function(res) {
						let list = res.devices;
						console.log(list);
						if (list.length <= 0) {
							return;
						}
						let devices = [];
						for (let i = 0; i < list.length; i++) {
							//that.data.inputValue：表示的是需要连接的蓝牙设备ID，
							//简单点来说就是我想要连接这个蓝牙设备，
							//所以我去遍历我搜索到的蓝牙设备中是否有这个ID
							let name = list[i].name || list[i].localName;
							if (util.isEmpty(name)) {
								continue;
							}
							if (name.indexOf(bleNamePrefix) >= 0 && list[i].RSSI != 0) {
								console.log(list[i]);
								devices.push(list[i]);
							}
						}
						console.log('总共有' + devices.length + "个设备需要设置")
						if (devices.length <= 0) {
							return;
						}
						that.connectBLE(devices);
					},
					fail: function() {
						// uni.hideLoading();
						//util.toastError('搜索蓝牙设备失败');
					}
				})
			},
			connectBLE(devices) {
				const that = this
				that.printLog('总共有' + devices.length + "个设备需要设置")
				// uni.hideLoading();
				that.isFound = true;
				//两个的时候需要选择
				let list = [];
				for (let i = 0; i < devices.length; i++) {
					let name = devices[i].name || devices[i].localName;
					list.push(name + "[" + devices[i].deviceId + "]")
				}
				that.deviceArray = list
				//默认选择
				that.currDeviceID = list[0]
			},
			createBLE(deviceId) {
				this.printLog("连接: [" + deviceId + "]");
				const that = this;
				this.closeBLE(deviceId, function(res) {
					console.log("预先关闭，再打开");
					setTimeout(function() {
						uni.createBLEConnection({
							deviceId: deviceId,
							success: function(res) {
								that.printLog("设备连接成功");
								setTimeout(function() {
									that.getBLEServiceId(deviceId);
								}, 200);
							},
							fail: function(res) {
								console.log(res);
								that.printLog("设备连接失败" + res.errMsg);
							}
						})
					}, 2000)
				});
			},
			//获取服务UUID
			getBLEServiceId(deviceId) {
				this.printLog("获取设备[" + deviceId + "]服务列表")
				const that = this;
				uni.getBLEDeviceServices({
					deviceId: deviceId,
					success: function(res) {
						console.log(res);
						let services = res.services;
						if (services.length <= 0) {
							that.printLog("未找到主服务列表")
							return;
						}
						that.printLog('找到设备服务列表个数: ' + services.length);
						console.log('找到设备服务列表: ', services);
						if (services.length == 1) {
							let service = services[0];
							that.printLog("服务UUID:[" + service.uuid + "]");
							that.printLog("Primary:" + service.isPrimary);
							that.getBLECharactedId(deviceId, service.uuid);
						} else { //多个主服务
							//TODO 以后如果有多个主服务，需要硬编码比对 ServiceUUID
							//找到第一个服务UUID并且是主服务
							let service = null;
							for (let i = 0; i < services.length; i++) {
								if (services[i].isPrimary == true && services[i].uuid.startsWith('0000AE80')) {
									service = services[i];
									break;
								}
							}
							if (service == null) {
								service = services[0];
							}
							that.printLog("服务UUID:[" + service.uuid + "]");
							that.printLog("Primary:" + service.isPrimary);
							that.getBLECharactedId(deviceId, service.uuid);
						}
					},
					fail: function(res) {
						that.printLog("获取设备服务列表失败" + res.errMsg);
					}
				})
			},
			getBLECharactedId(deviceId, serviceId) {
				this.printLog("获取设备特征值")
				const that = this;
				uni.getBLEDeviceCharacteristics({
					deviceId: deviceId,
					serviceId: serviceId,
					success: function(res) {
						console.log(res);
						//这里会获取到两个特征值，一个用来写，一个用来读
						let chars = res.characteristics
						if (chars.length <= 0) {
							that.printLog("未找到设备特征值")
							return
						}
						that.printLog("找到设备特征值个数:" + chars.length);

						for (let i = 0; i < chars.length; i++) {
							let char = chars[i];
							that.printLog("特征值[" + char.uuid + "]")
							if (char.uuid.startsWith('0000AE80') || char.uuid.startsWith('0000AE81') || 
								char.uuid.startsWith('0000AE82') || char.uuid.startsWith('6E40')) {
								let prop = char.properties;
								if (prop.notify) {
									that.printLog("该特征值属性: Notify");
									that.recvBLECharacterNotice(deviceId, serviceId, char.uuid);
								} else if (prop.write) {
									that.printLog("该特征值属性: Write");
									that.sendBLECharacterNotice(deviceId, serviceId, char.uuid);
								} else {
									that.printLog("该特征值属性: 其他");
								}
							} else {
								that.printLog("该特征值过滤")
							}

						}

						if (chars.length == 2) {

						} else {
							//TODO
						}
					},
					fail: function(res) {
						that.printLog("获取设备特征值失败")
					}
				})
			},
			recvBLECharacterNotice(deviceId, serviceId, charId) {
				//接收设置是否成功
				this.printLog("注册Notice 回调函数");
				const that = this;
				uni.notifyBLECharacteristicValueChange({
					deviceId: deviceId,
					serviceId: serviceId,
					characteristicId: charId,
					state: true, //启用Notify功能
					success: function(res) {
						uni.onBLECharacteristicValueChange(function(res) {
							console.log(res);
							that.printLog("收到Notify数据: " + that.ab2hex(res.value));
							that.recvBLEData(deviceId, serviceId, charId, res.value);
						});
					},
					fail: function(res) {
						console.log(res);
						that.printLog("特征值Notice 接收数据失败: " + res.errMsg);
					}
				})
			},
			sendBLECharacterNotice(deviceId, serviceId, charId) {
				const that = this;
				if (this.networkType == 'WIFI') {
					//发送ssid/pass
					this.printLog("延时1秒后，发送SSID/PASS");
					let cell = {
						"ssid": that.ssid,
						"pass": that.pass
					}
					//组装协议
					let array = this.iotProtocol(0x10, 0x01, JSON.stringify(cell));
					setTimeout(function() {
						that.sendBLEData(deviceId, serviceId, charId, array);
					}, 1000);
				} else if (this.networkType == '4G') {
					//发送4G启动信令
					this.printLog("延时1秒后，发送4G启动信令");
					//组装协议
					let array = [0x34, 0x47, 0x01, 0xFF];
					setTimeout(function() {
						that.sendBLEData(deviceId, serviceId, charId, array);
					}, 1000);
				}
			},
			closeBLE(deviceId, callback) {
				const that = this;
				uni.closeBLEConnection({
					deviceId: deviceId,
					success: function(res) {
						that.printLog("断开设备[" + deviceId + "]成功.");
						console.log(res)
					},
					fail: function(res) {
						that.printLog("断开设备成功.");
					},
					complete: callback
				})
			},
			/*iot 协议，支持带中文编码(GBK)*/
			iotProtocol(T1, T2, v) {
				//处理中文汉字
				let len = 0;
				for (let i = 0; i < v.length; i++) {
					let code = v.charCodeAt(i);
					if (code <= 256) {
						len += 1;
					} else {
						let char = v.charAt(i);
						let l = parseInt(encodeURIComponent(char).length / 3);
						len += l;
					}
				}
				len = len + 2; //总长度，加上两个字节的标志符JL

				let header = [0x4A, 0x4C];
				let LEN_H = parseInt(len / 256);
				let LEN_L = len % 256;
				let data = [LEN_H, LEN_L, T1, T2];
				//注意处理中文汉字
				for (let i = 0; i < v.length; i++) {
					let code = v.charCodeAt(i);
					if (code < 256) {
						data.push(code);
					} else { //中文
						let char = v.charAt(i);
						let gbk = encodeURIComponent(char).split('%');
						for (let j = 1; j < gbk.length; j++) {
							data.push(parseInt(gbk[j], 16));
						}
					}
				}

				let crc = this.CRC16(data); //计算CRC

				for (let i = 0; i < data.length; i++) {
					header.push(data[i])
				}
				header.push(crc[0]);
				header.push(crc[1]);
				header.push(0xFF);
				console.log(header);
				return header;
			},
			iotProtocolDecode(list) {
				let JL = list.splice(0, 2);
				let len = list[0] * 256 + list[1];
				list.splice(0, 2);
				let arr = list.splice(0, len);
				//console.log(arr);
				let type = arr.splice(0, 2);
				let str = "";
				for (let i = 0; i < arr.length; i++) {
					//console.log(arr[i], String.fromCharCode(arr[i]))
					str += String.fromCharCode(arr[i])
				}
				let title = this.$t('device.networkSettingFailed');
				let flag = true; //是否弹框
				let success = false;
				let cell = JSON.parse(str);
				try {
					if (cell.status == 0) {
						title = ""
						success = true
						this.setupNetworkStatus = 2
					} else if (cell.status == 1) {
						flag = false
					} else if (cell.status == 2) {
						this.setupNetworkResult = this.$t('device.networkSettingFailed') + this.$t('device.pleaseRestartDevice');
						this.setupNetworkStatus = 3
					} else if (cell.status == 3) {
						this.setupNetworkResult = this.$t('device.noMatchingWifiName');
						this.setupNetworkStatus = 3
					} else if (cell.status == 4) {
						this.setupNetworkResult = this.$t('device.wifiPasswordError');
						this.setupNetworkStatus = 3;
					} else {
						this.setupNetworkResult = this.$t('device.protocolError');
						this.setupNetworkStatus = 3;
					}
				} catch (e) {
					this.setupNetworkResult = this.$t('device.pleaseCheckTheNetworkEnvironment');
					this.setupNetworkStatus = 3;
				}

				this.printLog("配网结果: " + this.setupNetworkResult)
				// if (flag) {
				// 	uni.showModal({
				// 		title: title,
				// 		content: content,
				// 		showCancel: false,
				// 		success: function(res) {
				// 			if (res.confirm) {
				// 				console.log('用户点击确定');
				// 				if (cell.status == 2) {//配网失败
				// 					uni.switchTab({
				// 						url:'/pages/tabbar/device'
				// 					})
				// 				}
				// 			}
				// 		}
				// 	})
				// }
				// 配网结束
				this.connecting = false
				if (success) {
					// 保存WiFi信息
					this.saveNetworkInfo()
					// 保存设备信息（设备激活）
					this.bindUserDevice()
				}
			},

			/* 统一发送数据，带分包 */
			sendBLEData(deviceId, serviceId, charId, array) {
				const that = this;
				if (array.length <= 0) {
					that.printLog("发送配网数据 完成");
					return;
				}
				let list = array.splice(0, 20);
				let buffer = new Uint8Array(list).buffer;
				
				console.log('准备发送BLE数据：', {
					deviceId: deviceId,
					serviceId: serviceId,
					characteristicId: charId,
					bufferLength: buffer.byteLength
				});
				
				uni.writeBLECharacteristicValue({
					deviceId,
					serviceId,
					characteristicId: charId,
					value: buffer,
					success: function(res) {
						that.printLog("发送配网数据 分包发送");
						setTimeout(function() {
							that.sendBLEData(deviceId, serviceId, charId, array);
						}, 100);
					},
					fail: function(res) {
						console.log(res);
						that.printLog("发送失败." + res.errMsg);
					},
					complete: function() {

					}
				})
			},
			/* 统一接受数据，带组包 */
			recvBLEData(deviceId, serviceId, charId, buffer) {
				const that = this;
				let array = new Uint8Array(buffer);
				for (let i = 0; i < array.length; i++) {
					that.recvData.push(array[i]);
				}
				console.log(that.recvData);
				while (that.recvData.length >= 2) {
					if (that.recvData[0] == 0x4A && that.recvData[1] == 0x4C) {
						break;
					} else {
						let c = that.recvData.shift();
						//console.log("pop " , that.recvData);
					}
				}
				//协议判断
				if (that.recvData.length <= 6) {
					return;
				}
				//计算长度
				let len = that.recvData[2] * 256 + that.recvData[3];
				len = len + 4 + 3; //总长度
				console.log(len);
				if (that.recvData.length >= len) {
					//协议解析
					let list = that.recvData.splice(0, len);
					console.log("完成");
					that.iotProtocolDecode(list);
				}
			},
			debugEvent() {
				let list = [0x4A, 0x4C, 0x00, 0x0E, 0x10, 0x02];
				let buffer = new Uint8Array(list).buffer;
				this.recvBLEData('', '', '', buffer);
				list = [0x4A, 0x4A, 0x4A, 0x4A, 0x4A, 0x4A, 0x4A, 0x4A, 0x4A, 0x4A, 0x4A, 0x4A];
				buffer = new Uint8Array(list).buffer;
				this.recvBLEData('', '', '', buffer);
				list = [0x01, 0x96, 0xFF];
				buffer = new Uint8Array(list).buffer;
				this.recvBLEData('', '', '', buffer);

				let start = [0x4A, 0x4C];
				let data = [0x00, 0x0E, 0x10, 0x02, 0x7b, 0x22, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x22, 0x3a, 0x30,
					0x7d
				]
				let crc = this.CRC16(data);
				let end = [0xFF];

				let iot = [start, data, crc, end];
				for (let i = 0; i < iot.length; i++) {
					buffer = new Uint8Array(iot[i]).buffer;
					this.recvBLEData('', '', '', buffer);
				}
			},
			printLog(msg) {
				let logs = this.logs;
				logs.reverse();
				logs.push(msg);
				logs.reverse();
				if (logs.length >= 100) {
					logs.pop();
				}
				this.logs = logs
			},
			CRC16(buf) {
				let crc = 0x0000;
				for (let i = 0; i < buf.length; i++) {
					crc = (crc << 8) ^ this.CrcCCITTTable[((crc >> 8) ^ buf[i]) & 0x00FF];
				}
				let hi = ((crc & 0xFF00) >> 8); //高位置
				let lo = (crc & 0x00FF); //低位置
				return [hi, lo];
				//return [lo, hi]; // 大端模式
			},
			/**
			 * 将字符串转换成ArrayBufer
			 */
			string2buffer(str) {
				if (!str) return;
				let val = "";
				for (let i = 0; i < str.length; i++) {
					val += str.charCodeAt(i).toString(16);
				}
				console.log(val);
				str = val;
				val = "";
				let length = str.length;
				let index = 0;
				let array = []
				while (index < length) {
					array.push(str.substring(index, index + 2));
					index = index + 2;
				}
				val = array.join(",");
				// 将16进制转化为ArrayBuffer
				return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function(h) {
					return parseInt(h, 16)
				})).buffer
			},
			/**
			 * 将ArrayBuffer转换成字符串
			 */
			ab2hex(buffer) {
				let hexArr = Array.prototype.map.call(
					new Uint8Array(buffer),
					function(bit) {
						return ('00' + bit.toString(16)).slice(-2)
					}
				)
				return hexArr.join('');
			},
			// inputSSID: function(res) {
			// 	let ssid = res.detail.value;
			// 	this.setData({
			// 		ssid: ssid
			// 	})
			// },
			// inputPASS: function(res) {
			// 	var pass = res.detail.value;
			// 	this.setData({
			// 		pass: pass
			// 	})
			// },
			closeWifiModal() {
				this.showWifiModal = false
			},
			closeManualWifiModal() {
				this.showManualWifiModal = false
			},
			closeTipModal() {
				this.showTipModal = false
			},
			closeBluetoothPermissionModal() {
				this.showBluetoothPermissionModal = false
			},
			goToSettings() {
				this.showBluetoothPermissionModal = false
				// 跳转到系统设置
				if (this.platform == 'ios') {
					// TODO 跳转到ios系统设置
					uni.openURL('app-settings:');
				} else {
					const main = plus.android.runtimeMainActivity();  
					const Intent = plus.android.importClass("android.content.Intent");  
					const mIntent = new Intent('android.settings.BLUETOOTH_SETTINGS');  
					main.startActivity(mIntent);
				}
				
				uni.navigateBack({
					delta: 1
				})
			},
			showWifiModalFun(ssid) {
				this.showWifiModal = true
				this.ssid = ssid
			},
			showTipModalFun() {
				this.showTipModal = true
			},
			saveWifi() {
				console.log('============= saveWifi 方法被调用了')

				this.showWifiModal = false
				let wifi = null
				for (const w of this.wifiList) {
					if (this.ssid == w.SSID) {
						w.pass = this.pass
						wifi = w
						break
					}
				}
// 
				console.log('配网开始ssid:'+ this.ssid + 'pass:' + this.pass)
// 
				if (wifi != null) {
					//开始配网
					this.bleConfigEvent()
					return
				}
				this.showTipModalFun()
			},
			saveWifi2() {
				this.showManualWifiModal = false
			
				console.log('配网开始ssid:'+ this.ssid2 + 'pass:' + this.pass2)
		
				this.ssid = this.ssid2
				this.pass = this.pass2
				this.ssid2 = ''
				this.pass2 = ''
				this.bleConfigEvent()
			},
			bindUserDevice() {
				const userInfo = uni.getStorageSync('userInfo')
				let currDeviceID = this.currDeviceID
				const deviceId = currDeviceID.substring(0, currDeviceID.indexOf('['));
				const mac = currDeviceID.substring(currDeviceID.indexOf('[') + 1, currDeviceID.indexOf(']'))
				api.bindUserDevice(userInfo.phone, deviceId, this.ssid, mac, this.networkType).then(res => {
					uni.showToast({
						title: this.$t('device.deviceActivationSuccess'),
						icon: 'success',
						duration: 2000
					})
				})
			},
			confirm() {
				setTimeout(() => {
					uni.switchTab({
						url: '/pages/tabbar/device'
					})
				}, 1000)
			}
		},
		components: {
			Navigator2,
			neilModal
		}
	}
</script>

<style lang="scss" scoped>
.container {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	display: flex;
	flex-direction: column;
}

.step-indicator {
	display: flex;
	align-items: flex-start;
	justify-content: center;
	padding: 40rpx 80rpx;
	margin-bottom: 16px;
	
	.step-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		flex-shrink: 0;
		position: relative;

		.step-circle {
			width: 32px;
			height: 32px;
			border-radius: 50%;
			background: #EBEFF4;
			color: #6B7280;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 14px;
			font-weight: bold;

			&.active {
				background: #0256FF;
				color: white;
			}
		}

		.step-text {
			position: absolute;
			top: 52px;
			left: 50%;
			transform: translateX(-50%);
			font-size: 24rpx;
			color: #707A89;
			white-space: nowrap;
			text-align: center;

			&.active {
				color: #0256FF;
				font-weight: 500;
			}
		}
	}
	
	.step-line {
		width: 100rpx;
		height: 2rpx;
		background: #e0e0e0;
		margin: 0 20rpx;
		margin-top: 16px;
		flex-shrink: 0;
	}
}

.device-image {
	display: flex;
	justify-content: center;
	
	margin-top: 40px;

	image {
		width: 200px;
		height: 200px;
	}
}

.search-status {
	display: flex;
	justify-content: center;
	padding: 40rpx 60rpx 20rpx;
	
	text {
		font-size: 32rpx;
		line-height: 24px;
		color: #1F2937;
	}
}

.network-type {
	display: flex;
	justify-content: center;
	padding: 0 60rpx 200rpx;
	
	text {
		font-size: 28rpx;
		color: #707A89;
	}
}

.log-list {
	
}

.bluetooth-section {
	padding: 0 60rpx 200rpx;
	
	.bluetooth-title {
		display: flex;
		align-items: center;
		margin-bottom: 30rpx;
		
		.bluetooth-icon {
			width: 20px;
			height: 20px;
			margin-right: 15rpx;
		}
		
		text {
			font-size: 32rpx;
			font-weight: 600;
			color: #1F2937;
		}
	}
	
	.device-card {
		border: 2rpx solid #0256FF;
		border-radius: 16rpx;
		padding: 30rpx;
		background: linear-gradient(0deg, rgba(2, 86, 255, 0.05), rgba(2, 86, 255, 0.05)), #FFFFFF;
		position: relative;
		min-height: 100rpx;
		
		.device-info {
			.device-name {
				margin-bottom: 20rpx;
				
				.device-title {
					font-size: 28rpx;
					font-weight: 600;
					color: #1F2937;
				}
				
				.device-value {
					position: absolute;
					right: 30rpx;
					top: 50%;
					transform: translateY(-50%);
					font-size: 28rpx;
					color: #0256FF;
					font-weight: 600;

					width: 180px;
					text-align: right;
					margin-left: auto;
					flex: 1;
					/* 右元素自适应剩余空间 */
					overflow: visible;
					/* 允许内容溢出 */
					white-space: nowrap;
					/* 防止内容换行挤压 */
					overflow: scroll;
				}
			}
			
			.device-tip {
				font-size: 24rpx;
				color: #707A89;
			}
		}
	}
}

.bottom-section {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background: white;
	padding: 40rpx 60rpx;
}

.next-button {
	height: 100rpx;
	background: #0256FF;
	border-radius: 8px;
	display: flex;
	align-items: center;
	justify-content: center;
	
	&:active {
		background: #0245ff;
	}
	
	text {
		color: white;
		font-size: 32rpx;
	}
}

.confirm-button {
	height: 100rpx;
	background: #0256FF;
	border-radius: 8px;
	display: flex;
	align-items: center;
	justify-content: center;
	
	&:active {
		background: #0245ff;
	}
	
	text {
		color: white;
		font-size: 32rpx;
	}
}

/* 蓝牙权限弹框内容样式 */
.bluetooth-modal-content {
	display: flex;
	flex-direction: column;
	align-items: center;
	text-align: center;
	padding: 40rpx 40rpx 20rpx;
	
	.bluetooth-modal-title {
		font-size: 32rpx;
		font-weight: 600;
		color: #000000;
		line-height: 24px;
		margin-top: 16px;
		margin-bottom: 12px;
		word-break: break-word;
	}
	
	.bluetooth-modal-text {
		font-size: 16px;
		line-height: 24px;
		color: #707A89;
		margin-bottom: 16px;
	}
}

.modal_wifiname {
	margin: 20px;
	color: #333333;
	font-size: 18px;
}

.modal_wifiname text {
	font-weight: 600;
}

.input-name input {
	padding-left: 10px;
	border: solid 1px #CCCCCC;
	margin: 20px 20px;
	font-size: 18px;
	color: #767676;
	height: 40px;
	line-height: 40px;
	border-radius: 8px;
}

.blank {
	width: 100%;
	height: 1px;
}

/* 调整 neil-modal 样式以匹配图片效果 */
::v-deep .neil-modal__container {
	width: 600rpx !important;
	border-radius: 24rpx !important;
}

::v-deep .neil-modal__content {
	padding: 0 !important;
	min-height: auto !important;
}

::v-deep .neil-modal__footer {
	height: 100rpx !important;
}

::v-deep .neil-modal__footer-left,
::v-deep .neil-modal__footer-right {
	height: 100rpx !important;
	line-height: 100rpx !important;
	font-size: 32rpx !important;
	font-weight: 500 !important;
}

::v-deep .neil-modal__footer-left {
	color: #666666 !important;
}

::v-deep .neil-modal__footer-right {
	color: #007aff !important;
}
</style>